package com.yidian.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yidian.dao.OrderItemMapper;
import com.yidian.dao.OrderLogMapper;
import com.yidian.dao.OrderMapper;
import com.yidian.entity.PageResult;
import com.yidian.pojo.order.Order;
import com.yidian.pojo.order.OrderItem;
import com.yidian.pojo.order.OrderLog;
import com.yidian.server.goods.SkuService;
import com.yidian.server.order.CartService;
import com.yidian.server.order.OrderService;
import com.yidian.utils.IdWorkerBySnowFlake;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author whb
 * @create 2021-09-02 09:48
 * @desciption 订单业务接口service实现类
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private IdWorkerBySnowFlake idSnowFlake;
    @Autowired
    private CartService cartService;
    @Reference
    private SkuService skuService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderLogMapper orderLogMapper;

    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 保存订单
     * @param order 订单对象
     * @return
     */
    @Override
    public Map<String, Object> addOrder(Order order) {
        List<Map<String, Object>> newOrderItemList = cartService.findNewOrderItemList(order.getUsername());//获取价格同步的购物车
        //获取商品被选中的购物车(订单明细)
        List<OrderItem> orderItems = newOrderItemList.stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //判断条件：执行扣减库存和增加销量
        if (!skuService.deductionStock(orderItems)){
            throw new RuntimeException("库存不足！");
        }

        try {
            order.setId(idSnowFlake.nextId()+"");//设置订单表id
            IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();//订单总数量
            int totalMoney = moneyStream.sum();//订单总金额
            int preMoney=cartService.preferential(order.getUsername());//订单优惠金额
            order.setTotalNum(totalNum);//设置订单总数量
            order.setTotalMoney(totalMoney);//设置订单总金额
            order.setPreMoney(preMoney);//设置订单优惠金额
            order.setPayMoney(totalMoney-preMoney);//设置订单支付金额，支付金额=总金额-优惠金额
            order.setCreateTime(new Date());//设置订单创建日期
            order.setOrderStatus("0");//设置订单状态 0：待付款 1：待发货 2：已发货 3：已完成 4：已关闭
            order.setPayStatus("0");//设置订单支付状态 0：未支付 1：已支付 2：已退款
            order.setConsignStatus("0");//设置订单发货状态 0：未发货 1：已发货
            orderMapper.insert(order);//保存订单

            double proportion=order.getPayMoney()/totalNum;//商品支付比例：设置到订单明细支付金额，作为以后退货回款标准
            //保存订单明细
            for (OrderItem orderItem:orderItems){
                orderItem.setId(idSnowFlake.nextId()+"");//订单明细id
                orderItem.setOrderId(order.getId());//订单id
                orderItem.setPayMoney((int)(orderItem.getMoney()*proportion));//设置订单明细每种商品的支付金额
                orderItemMapper.insert(orderItem);//保存订单明细
            }
        } catch (Exception e) {
            e.printStackTrace();
            //发送回滚消息
            rabbitTemplate.convertAndSend("queue.stockBack", JSON.toJSONString(orderItems));
            throw new RuntimeException("提交订单失败！");
        }

        //清除购物车已选中的商品
        cartService.deleteCheckedCart(order.getUsername());

        //返回订单号和支付金额
        Map<String,Object> map=new HashMap<>();
        map.put("orderSn",order.getId());//订单号
        map.put("money",order.getPayMoney());//订单支付金额

        return map;
    }

    /**
     * 更新订单支付状态
     * @param orderId 订单号
     * @param transactionId 流水号（查账时使用）
     */
    @Override
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);//根据订单号查询订单
        if (order!=null&&"0".equals(order.getPayStatus())){//查询到的订单存在，并且未支付
            order.setPayStatus("1");//支付状态更新为已支付
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());//订单更新时间
            order.setPayTime(new Date());//支付时间
            order.setTransactionId(transactionId);//微信支付平台返回的流水号
            orderMapper.updateByPrimaryKeySelective(order);

            //记录订单变动日志
            OrderLog orderLog = new OrderLog();//新建订单日志对象
            orderLog.setId(idSnowFlake.nextId()+"");//订单日志id
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//记录日志的时间
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号："+transactionId);//流水号
            orderLog.setOrderId(orderId);//订单号
            orderLogMapper.insertSelective(orderLog);
        }
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }
}
